<script lang="ts">
export default {
  name: "RepoProductEntityTable"
}
</script>

<template>
  <!-- 数据表单 -->
  <el-table
      ref="dataTableRef"
      v-loading="false"
      :data="dataState.entityList"
      border
      highlight-current-row
      @row-click="handleRowClick"
  >
    <!-- 展开列表 -->
    <el-table-column type="expand">
      <template #default="props">
        <el-table
            ref="dataTableRef"
            :data="props.row.comps"
            border
            highlight-current-row
            @row-click="handleRowClick"
        >
          <el-table-column align="center" label="组件名称" min-width="100" prop="modelName"/>
          <el-table-column align="center" label="组件类型" prop="modelType" width="180"/>
          <el-table-column align="center" label="接口版本" prop="modelVersion" width="180"/>


          <el-table-column align="center" label="操作" width="150">
            <template #default="scope">
              <el-button :icon="More" circle plain type="primary" @click.stop="handleMoreComp(scope.row)"/>
              <el-button :icon="Edit" circle plain type="primary" @click.stop="handleEditComp(scope.row)"/>
              <el-button :icon="Delete" circle plain type="danger" @click.stop="handleDeleteComp(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>

    <!-- 列表 -->
    <el-table-column label="产品型号" min-width="120" prop="deviceType"/>
    <el-table-column label="生产厂商" min-width="100" prop="manufacturer"/>
    <el-table-column align="center" label="产品图片" width="100">
      <template #default="scope">
        <el-popover :width="425" placement="right" trigger="hover">
          <img :src="scope.row.imageUrl" alt="" width="400"/>
          <template #reference>
            <img
                :src="scope.row.imageUrl"
                alt=""
                style="max-width: 60px"/>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column align="center" label="厂家链接" prop="url" width="100">
      <template #default="scope">
        <el-button :icon="Link" circle plain type="primary" @click.stop="handleLink(scope.row)"/>
      </template>
    </el-table-column>

    <el-table-column v-if="dataState.isAdmin === false" :formatter="formatDate4elTableColumn" align="center" label="创建时间"
                     prop="createTime"
                     width="180"/>
    <el-table-column v-if="dataState.isAdmin === true" align="center" label="权重" width="180">
      <template #default="scope">
        <p> {{ scope.row.weight }} </p>
        <el-button :icon="ArrowUp" circle plain type="primary" @click.stop="handleWeight(scope.row,'up')"/>
        <el-button :icon="ArrowDown" circle plain type="primary" @click.stop="handleWeight(scope.row,'down')"/>
      </template>
    </el-table-column>

    <el-table-column :formatter="formatDate4elTableColumn" align="center" label="更新时间"
                     prop="updateTime"
                     width="180"/>

    <!-- 上传对话框/下载对话框 -->
    <el-table-column align="center" label="操作" width="150">
      <template #default="scope">
        <el-button :icon="Plus" circle plain type="primary" @click.stop="handleCreateComp(scope.row)"/>
        <el-button :icon="Edit" circle plain type="primary" @click.stop="handleEditDialog(scope.row)"/>
        <el-button :icon="Delete" circle plain type="danger" @click.stop="handleDeleteDialog(scope.row)"/>
      </template>
    </el-table-column>

  </el-table>

  <!-- 分页工具条 -->
  <pagination v-if="dataState.total > 0" v-model:limit="dataState.queryParams.pageSize"
              v-model:page="dataState.queryParams.pageNum" :total="dataState.total"
              @pagination="handleQuery"/>
</template>

<script lang="ts" setup>
import {onMounted, reactive} from "vue";
import {useRouter} from "vue-router";
import useUserStore from '@/store/modules/user'

import {
  RepoProductEntity,
  RepoProductQueryParam
} from "@/api/cloud/repository/repoproduct/types";
import {
  listRepoProductEntityPages, updateRepoProductWeight,
} from "@/api/cloud/repository/repoproduct";
import {Link, More, Plus, Delete, Edit, ArrowUp, ArrowDown} from '@element-plus/icons-vue';
import {formatDate4elTableColumn,} from '@/utils/formatter';
import {ElMessage} from "element-plus";

const emit = defineEmits(['rowClick', 'update', 'delete', 'insertComp', 'deleteComp', 'updateComp']);// 定义组件的事件通知
const router = useRouter();
/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({refreshTable});

// 数据状态：定义
let dataState = reactive({
  // 页面转载状态
  loading: false,
  // 选中ID数组
  ids: [],
  // 记录总数
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 查询参数
  queryParams: {pageNum: 1, pageSize: 10} as RepoProductQueryParam,
  // 实体数据
  entityList: [] as RepoProductEntity[],
  // 是否为管理员用户
  isAdmin: false,
});

function formatText(row: any, column: any) {
  // 获取单元格数据
  const data = row[column.property]

  if (column.property === 'version' && data === "") {
    return "默认版本";
  }
  if (column.property === 'stage' && data === "") {
    return "默认状态";
  }

  return data
}


/**
 * 捕获列表中的行选择
 * @taskParam row
 */
function handleRowClick(row: any) {
  emit('rowClick', row);
}

/**
 * 捕获按钮的打开对话框操作：create/update
 * @taskParam row 行信息
 */
function handleEditDialog(row: any) {
  emit('update', 'table', 'update', row);
}


function handleCreateComp(row: any) {
  emit('insertComp', 'table', row);
}

function handleLink(row: any) {
  window.open(row.url);
}

async function handleWeight(row: any, arrow: string) {
  if (arrow === 'up') {
    row.weight += 1;
  } else {
    row.weight -= 1;
  }

  let formData = {
    uuid: row.uuid,
    weight: row.weight,
  }

  await updateRepoProductWeight(formData).then(() => {
    ElMessage.success('更新成功');
  })

}

/**
 * 刷新页面信息
 */
function handleQuery() {
  emit('rowClick', {});

  dataState.loading = true;

  dataState.entityList = [];
  listRepoProductEntityPages(dataState.queryParams).then(({data}) => {
    data.list.forEach(value => {
      value.imageUrl = "http://repository.fox-tech.cn/image/" + value.image;
      value.comps?.forEach(comp => {
        comp.productId = value.uuid;
      });
      dataState.entityList.push(value);
    });

    dataState.total = data.total;
    dataState.loading = false;
  });
}

function handleDeleteDialog(row: any) {
  emit('delete', row);
}

function handleDeleteComp(row: any) {
  emit('deleteComp', row);
}

function handleEditComp(row: any) {
  emit('updateComp', row);
}

function handleMoreComp(row: any) {
  router.push('/repository/cloud/repository/repocomp?modelType=' + row.modelType + '&modelName=' + row.modelName + '&modelVersion=' + row.modelVersion);
}

/**
 * 刷新表单
 */
function refreshTable(queryParams: RepoProductQueryParam) {
  dataState.queryParams = queryParams;
  if (dataState.queryParams.groupName === '') {
    dataState.queryParams.groupName = undefined;
  }
  if (dataState.queryParams.modelType === '') {
    dataState.queryParams.modelType = undefined;
  }
  if (dataState.queryParams.modelVersion === '') {
    dataState.queryParams.modelVersion = undefined;
  }
  if (dataState.queryParams.modelName === '') {
    dataState.queryParams.modelName = undefined;
  }
  if (dataState.queryParams.component === '') {
    dataState.queryParams.component = undefined;
  }

  handleQuery();
}

function isAdmin() {
  for (let role of useUserStore().roles) {
    if (role === "admin") {
      return true;
    }
  }

  return false;
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 是否为管理员用户
  dataState.isAdmin = isAdmin();

  // 查询实体数据
  handleQuery();
});

</script>
